﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ADOWrapper.ObjectResolver
{
    public static class SimpleConverter
    {
        static SimpleConverter()
        {
            ValueResolvers = new System.Collections.Concurrent.ConcurrentDictionary<Type, IValueResolver>();
            mi = typeof(SimpleConverter).GetMethod("Convert", BindingFlags.Static | BindingFlags.Public);
        }

        public static T Convert<T>(object value)
        {
            Type expectedType = typeof(T);
            IValueResolver resolver;
            if (ValueResolvers.TryGetValue(expectedType, out resolver))
                return (T)resolver.ResolveValue(value, expectedType);

            if (value == null || value == DBNull.Value)
                return default(T);
            return (T)value;
        }


        public static System.Collections.Concurrent.ConcurrentDictionary<Type, IValueResolver> ValueResolvers { get; private set; }

        static MethodInfo mi;

        internal static MethodInfo GetConvertMethodInfo(Type type)
        {
            return mi.MakeGenericMethod(type);
        }
    }
}
